package com.yanwq.pulltorefreshview.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：yanweiqiang。
 * 日期：2016/5/3 0003。
 */
public class PullToRefreshListView extends ListView implements ScrollDetector, AbsListView.OnScrollListener {
    TheEndCallback callback;
    List<OnScrollListener> onScrollListeners = new ArrayList<>();

    public PullToRefreshListView(Context context) {
        super(context);
        init();
    }

    public PullToRefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PullToRefreshListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setOnScrollListener(this);
    }

    public void addOnScrollListener(OnScrollListener onScrollListener) {
        onScrollListeners.add(onScrollListener);
    }

    public void removeOnScrollListener(OnScrollListener onScrollListener) {
        onScrollListeners.remove(onScrollListener);
    }

    @Override
    public boolean theTop() {
        View view = getChildAt(0);
        Log.i("temp", "view:"+view);
        return view == null || getCount() == 0 || getFirstVisiblePosition() == 0 && view.getTop() >= 0;
    }

    @Override
    public boolean theEnd() {
        View view = getChildAt(getLastVisiblePosition() - getFirstVisiblePosition());
        return view == null || getCount() == 0 || getLastVisiblePosition() == getCount() - 1 && view.getBottom() <= getBottom();
    }

    @Override
    public void setTheEndCallback(TheEndCallback callback) {
        this.callback = callback;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        for (OnScrollListener onScrollListener : onScrollListeners) {
            onScrollListener.onScrollStateChanged(view, scrollState);
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        for (OnScrollListener onScrollListener : onScrollListeners) {
            onScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
        }

        if (callback != null && isListViewReachBottomEdge(this)) {
            callback.end();
        }
    }

    public boolean isListViewReachBottomEdge(final ListView listView) {
        boolean result = false;

        if (listView.getCount() > 0 && listView.getLastVisiblePosition() == (listView.getCount() - 1)) {
            final View bottomChildView = listView.getChildAt(listView.getLastVisiblePosition() - listView.getFirstVisiblePosition());
            result = (listView.getHeight() >= bottomChildView.getBottom());
        }

        return result;
    }
}